switch from yaml to json serialization

Andrew Cantino 11 years ago
parent
commit
ec32d7f979
2 changed files with 42 additions and 1 deletions
  1. 41 0
      db/migrate/20131223032112_switch_to_json_serialization.rb
  2. 1 1
      lib/serialize_and_normalize.rb

+ 41 - 0
db/migrate/20131223032112_switch_to_json_serialization.rb

@@ -0,0 +1,41 @@
1
+class SwitchToJsonSerialization < ActiveRecord::Migration
2
+  FIELDS = {
3
+    :agents => [:options, :memory],
4
+    :events => [:payload]
5
+  }
6
+
7
+  def up
8
+    puts "This migration will update Agent and Event storage from YAML to JSON.  It should work, but please make a backup"
9
+    puts "before proceeding."
10
+    print "Continue? (y/n) "
11
+    STDOUT.flush
12
+    exit unless STDIN.gets =~ /^y/i
13
+
14
+    translate YAML, JSON
15
+  end
16
+
17
+  def down
18
+    translate JSON, YAML
19
+  end
20
+
21
+  def translate(from, to)
22
+    FIELDS.each do |table, fields|
23
+      quoted_table_name = ActiveRecord::Base.connection.quote_table_name(table)
24
+      fields = fields.map { |f| ActiveRecord::Base.connection.quote_column_name(f) }
25
+
26
+      rows = ActiveRecord::Base.connection.select_rows("SELECT id, #{fields.join(", ")} FROM #{quoted_table_name}")
27
+      rows.each do |row|
28
+        id, *field_data = row
29
+
30
+        yaml_fields = field_data.map { |f| from.load(f) }.map { |f| to.dump(f) }
31
+
32
+        update_sql = "UPDATE #{quoted_table_name} SET #{fields.map {|f| "#{f}=?"}.join(", ")} WHERE id = ?"
33
+
34
+        sanitized_update_sql = ActiveRecord::Base.send :sanitize_sql_array, [update_sql, *yaml_fields, id]
35
+
36
+        ActiveRecord::Base.connection.execute sanitized_update_sql
37
+      end
38
+    end
39
+
40
+  end
41
+end

+ 1 - 1
lib/serialize_and_normalize.rb

@@ -8,7 +8,7 @@ module SerializeAndNormalize
8 8
         normalize_name = "normalize_#{column_name}".to_sym
9 9
         validate_name = "validate_#{column_name}".to_sym
10 10
 
11
-        serialize column_name
11
+        serialize column_name, JSON
12 12
         after_initialize setup_name
13 13
         before_validation normalize_name
14 14
         before_save normalize_name